// 依赖jquery
+ function(){ 
    var L = L || {};
    
    var _clientId,_clientSecret,_user,_repo,_issue,_divId,_token;
    var _domain = "http://www.zhoyq.com" ;
    var _cookieName = "gitee-access-code";
    var _tokenName = "gitee-access-token";
    var _apiAllComments,_apiLoginPath,_apiAddComment,_apiOauth;

    function setCookie(name,value) {
        var Days = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days*24*60*60*1000);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
    }
 

    function getCookie(name) {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    } 
  
    function delCookie(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        if(cval!=null)
          document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }

    function getAllComments(page,perPage){
        var data = "";
        $.ajax({
            url : _apiAllComments,
            data:{
                page:page,
                per_page:perPage
            },
            cache : false, 
            async : false,
            type : "GET",
            dataType : 'json',
            success : function (result,status,xhr){ 
                if(xhr.status == 200) data = result;
            }
        });
        return data;  
    }

    function getCommentsHtmlFrom(comments){
        var buf = ""; 
        var now = new Date();
        $(comments).each(function(i,data){
            var createAtBuf = new Date(data.created_at.substring(0,19).replace(/T/," ").replace(/-/g,"/")); 
            var formatTime = Math.round((now.getTime() - createAtBuf.getTime())/(1000*60*60)); 
            var unit = "小时之前";
            if(formatTime > 24) {
                formatTime = formatTime/24;
                unit = "天之前";
            }
            if(formatTime > 365) {
                formatTime = formatTime/365;
                unit = "年之前";
            }
            formatTime = formatTime.toFixed(1);
            if(formatTime == 0){
                formatTime = "";
                unit = "刚刚";
            }
            buf = "<div class=\"gitee-comments-item\"><img class=\"gitee-comments-avatar\" alt=\""
                +data.user.name+"\" title=\""+data.user.name+"\" src=\""
                +data.user.avatar_url+"\" /><br/><span class=\"gitee-comments-body\">"
                +data.body+"</span><span class=\"gitee-comments-time\">"
                +formatTime+unit+"</span></div>" + buf;
        });
        buf = "<div class=\"gitee-comments-list\">" + buf + "</div>";
        return buf;
    }

    L.commentArticle = function(){
        var body = $(".gitee-comments-content textarea").val(); 
        if(body && body!=""){
            $.ajax({
                url : _apiAddComment,
                data:{
                    access_token:_token,
                    body:body
                },
                cache : false, 
                async : true,
                type : "POST",
                dataType : 'json',
                success : function (result,status,xhr){   
                    if(xhr.status != 201){
                        setCookie(_tokenName,"");
                    }
                    L.init(_clientId,_clientSecret,_user,_repo,_issue,_divId);
                },
                error : function (result,status,xhr){   
                    setCookie(_tokenName,"");
                    L.init(_clientId,_clientSecret,_user,_repo,_issue,_divId);
                }
            }); 
        } 
    };

    L.login = function(){
        window.open( _apiLoginPath + "?client_id="+_clientId+"&redirect_uri=http%3A%2F%2Fwww.zhoyq.com&response_type=code",
                    '_blank','width=1000,height=600,menubar=no,toolbar=no,status=no,scrollbars=no');
    };
    
    L.logout = function(){
        setCookie(_tokenName,"");
        L.init(_clientId,_clientSecret,_user,_repo,_issue,_divId);
    };

    L.flushWin = function(){ 
        var code = getCookie(_cookieName);
        $.post(_apiOauth,{
            grant_type:'authorization_code',
            code:code,
            client_id:_clientId,
            redirect_uri:_domain,
            client_secret:_clientSecret 
        },function(msg){ 
            _token = msg.access_token; 
            setCookie(_tokenName,_token);
            L.init(_clientId,_clientSecret,_user,_repo,_issue,_divId);
        });  
    };

    L.init = function(id,secret,user,repo,issue,divId){
        $('#'+_divId).html('');
        _clientId = id;
        _clientSecret = secret;
        _user = user;
        _repo = repo;
        _issue = issue;
        _divId = divId;  
        _apiAllComments = _domain + "/gitee/api/v5/repos/"+_user+"/"+_repo+"/issues/"+_issue+"/comments";
        _apiLoginPath = "https://gitee.com/oauth/authorize";
        _apiAddComment = _domain + "/gitee/api/v5/repos/"+_user+"/"+_repo+"/issues/"+_issue+"/comments";
        _apiOauth = _domain + "/gitee/oauth/token";
        // 判断是否存在cookie
        var comments = getAllComments(1,999);  
        $('#'+_divId).append("<a class=\"gitee-comments-title\">#评论</a>"); 
        
        // 判断是否登陆
        var token = getCookie(_tokenName);
        if(token && token.length == 32){
            // 登陆
            _token = token;
            
            // 退出按钮
            $('#'+_divId).append("<div onClick=\"L.logout();\" class=\"gitee-comments-login-btn\"><a>退出</a></div>"); 
            // 评论按钮
            $('#'+_divId).append("<div onClick=\"L.commentArticle();\" class=\"gitee-comments-login-btn\"><a>评一下</a></div>"); 
            // 评论输入框
            $('#'+_divId).append("<div class=\"gitee-comments-content\"><textarea></textarea></div>");  
        }else{
            // 未登录
            // 评论按钮
            $('#'+_divId).append("<div onClick=\"L.login();\" class=\"gitee-comments-login-btn\"><a>评一下</a></div>"); 
        } 
        // 直接拼接评论
        $('#'+_divId).append(getCommentsHtmlFrom(comments)); 
    };
 
    L.cookieName = _cookieName;
    L.setCookie = setCookie;
    window.L = L; 
}();